﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

public partial class CallLogUpload : System.Web.UI.Page
{
    DataColumn cFromNo = new DataColumn("from_no", typeof(string));
    DataColumn cFromNet = new DataColumn("from_net", typeof(string));
    DataColumn cToNo = new DataColumn("to_no", typeof(string));
    DataColumn cToNet = new DataColumn("to_net", typeof(string));
    DataColumn cDate = new DataColumn("date", typeof(DateTime));
    DataColumn cTime = new DataColumn("time", typeof(double));
    DataColumn cHour = new DataColumn("hour", typeof(int));
    DataColumn cMin = new DataColumn("min", typeof(int));

    string myProvider
    {
        get
        {
            string res = "ais";
            if (Session["SESS_MYNUM"] == null)
            {
                Session["SESS_MYNUM"] = "ais";
            }
            res = Session["SESS_MYNUM"] as string;
            return res;
        }
        set
        {
            Session["SESS_MYNUM"] = value;
        }
    }

    ProviderRange PrRange
    {
        get
        {
            ProviderRange p = Session["SESS_PRO_RANGE"] as ProviderRange;
            if (Session["SESS_PRO_RANGE"] == null)
            {
                p = PhoneLoader.DeserializeProviderRangeFromXML();
                Session["SESS_PRO_RANGE"] = p;
            }

            return p;
        }
    }

    DataTable callingLog
    {
        get
        {
            if (Session["SESS_CALL_LOG_TABLE"] == null)
            {
                Session["SESS_CALL_LOG_TABLE"] = new DataTable();
                DataTable tb = Session["SESS_CALL_LOG_TABLE"] as DataTable;
                tb.TableName = "CallingLog";
                tb.Columns.Add(cFromNo);
                tb.Columns.Add(cFromNet);
                tb.Columns.Add(cToNo);
                tb.Columns.Add(cToNet);
                tb.Columns.Add(cDate);
                tb.Columns.Add(cTime);
                tb.Columns.Add(cHour);
                tb.Columns.Add(cMin);
            }
            return Session["SESS_CALL_LOG_TABLE"] as DataTable;
        }
        set
        {
            Session["SESS_CALL_LOG_TABLE"] = value;
        }
    }

    UserPhone phone
    {
        get
        {
            if (Session["SESS_USER_PHONE"] == null)
            {
                Session["SESS_USER_PHONE"] = new UserPhone(UUID);
            }
            return Session["SESS_USER_PHONE"] as UserPhone;
        }
        set
        {
            Session["SESS_USER_PHONE"] = value;
        }
    }

    string UUID
    {
        get
        {
            string uuid = "";
            if (Request.Cookies["UUID"] != null)
            {
                uuid = Request.Cookies["UUID"].Value;
            }
            return uuid;
        }
    }

    Dictionary<string, DateTime> SpecificDateTime
    {
        get
        {
            if (Session["SESS_SPEC_DATE_TIME"] == null)
            {
                Session["SESS_SPEC_DATE_TIME"] = new Dictionary<string, DateTime>();
            }
            return Session["SESS_SPEC_DATE_TIME"] as Dictionary<string, DateTime>;
        }
        set
        {
            Session["SESS_SPEC_DATE_TIME"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        lblError.Text = "";

        if (!IsPostBack)
        {
            lstFiles.Items.Clear();

            string folder = HttpContext.Current.Server.MapPath(@"Examples");

            if (Directory.Exists(folder))
            {
                DirectoryInfo di = new DirectoryInfo(folder);
                FileInfo[] rgFiles = di.GetFiles("*.*");
                foreach (FileInfo fi in rgFiles)
                {
                    ListItem l = new ListItem(fi.Name,  @"~/Examples/" + fi.Name);
                    lstFiles.Items.Add(l);
                }
            }
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string provide = rdoProvide.SelectedValue.ToLower();
        myProvider = provide;

        switch (provide)
        {
            case "ais": { ReadAisFile(); } break;
            case "dtac": { ReadDtacFile(); } break;
            case "tmove": { ReadTrueMoveFile(); } break;
            case "default": {ReadStandardFile(); } break;
        }
        
        
    }

    private void ReadStandardFile()
    {
        try
        {

            if (fUpload.PostedFile.ContentLength > 0)
            {
                if (Path.GetExtension(fUpload.FileName).ToLower() == ".csv")
                {
                    StreamReader reader = new StreamReader(fUpload.PostedFile.InputStream);
                    int line = 0;
                    callingLog = null;
                    while (!reader.EndOfStream)
                    {
                        string readLine = reader.ReadLine();
                        if (line++ > 0)
                        {
                            try
                            {
                                readLine = readLine.Replace("'", "");
                                string[] contents = readLine.Split(new char[] { ',' });
                                //if (contents.Length >= 7)
                                {
                                    myProvider = contents[1].ToString();

                                    DataRow drow = callingLog.NewRow();
                                    drow[cFromNo] = contents[0];
                                    drow[cFromNet] = contents[1];
                                    drow[cToNo] = contents[2];
                                    drow[cToNet] = string.IsNullOrEmpty(contents[3]) ? PrRange.GetProviderFromNumber(contents[2]) : contents[3];
                                    DateTime onDate = DateTime.ParseExact(contents[4] + " " + contents[5], "yyyy-MM-dd HH:mm", null);
                                    drow[cDate] = onDate;
                                    drow[cTime] = contents[5].Replace(':', '.');
                                    drow[cHour] = contents[5].Split(new char[] { ':', '.' })[0];
                                    drow[cMin] = contents[6];
                                    callingLog.Rows.Add(drow);

                                    if (!SpecificDateTime.Keys.Contains(onDate.ToString("yyyyMM")))
                                    {
                                        SpecificDateTime.Add(onDate.ToString("yyyyMM"), onDate);
                                    }

                                }
                            }
                            catch
                            {
                            }
                        }

                    }

                    if (callingLog.Rows.Count > 0)
                    {
                        Response.Redirect("PromoAnalysis.aspx");
                    }
                    else
                    {
                        lblError.Text = "Error: Please upload well-formed CSV file (see example)";
                    }
                }
                else
                {
                    lblError.Text = "Error: Please upload CSV file";
                }
            }
            else
            {
                lblError.Text = "Error: Please upload file";
            }
        }
        catch
        {
            lblError.Text = "Error: Please upload well-formed CSV file (see example)";
        }
    }


    private void ReadTrueMoveFile()
    {
        try
        {

            if (fUpload.PostedFile.ContentLength > 0)
            {
                if (Path.GetExtension(fUpload.FileName).ToLower() == ".txt")
                {
                    StreamReader reader = new StreamReader(fUpload.PostedFile.InputStream);
                    int line = 0;
                    callingLog = null;
                    while (!reader.EndOfStream)
                    {
                        string readLine = reader.ReadLine();
                        if (line++ > 1)
                        {
                            try
                            {
                                //readLine = readLine.Replace("'", "");
                                string[] contents = readLine.Split(new string[] { " | " }, StringSplitOptions.RemoveEmptyEntries);
                                if (contents[4].Trim().ToLower() == "voice")
                                {
                                    DataRow drow = callingLog.NewRow();
                                    drow[cFromNo] = contents[0].Trim();
                                    drow[cFromNet] = "tmove";
                                    drow[cToNo] = contents[2].Trim();
                                    drow[cToNet] = PrRange.GetProviderFromNumber(contents[2].Trim());
                                    DateTime onDate = DateTime.ParseExact(contents[1].Trim(), "dd/MM/yyyy HH:mm:ss", null);
                                    drow[cDate] = onDate;
                                    drow[cTime] = onDate.Hour + "." + onDate.Minute;
                                    drow[cHour] = onDate.Hour;
                                    DateTime min = DateTime.ParseExact(contents[6].Trim(), "HH:mm:ss", null);
                                    drow[cMin] = min.Hour * 60 + min.Minute;
                                    callingLog.Rows.Add(drow);

                                    if (!SpecificDateTime.Keys.Contains(onDate.ToString("yyyyMM")))
                                    {
                                        SpecificDateTime.Add(onDate.ToString("yyyyMM"), onDate);
                                    }

                                }

                            }
                            catch
                            {
                            }

                        }

                    }

                    if (callingLog.Rows.Count > 0)
                    {
                        Response.Redirect("PromoAnalysis.aspx", false);
                    }
                    else
                    {
                        lblError.Text = "Error: Please upload well-formed file that you get from provider";
                    }
                }
                else
                {
                    lblError.Text = "Error: Please upload Text file";
                }
            }
            else
            {
                lblError.Text = "Error: Please upload file";
            }
        }
        catch
        {
            lblError.Text = "Error: Please upload well-formed file that you get from provider";
        }
    }


    private void ReadDtacFile()
    {
        try
        {

            if (fUpload.PostedFile.ContentLength > 0)
            {
                if (Path.GetExtension(fUpload.FileName).ToLower() == ".txt")
                {
                    StreamReader reader = new StreamReader(fUpload.PostedFile.InputStream);
                    int line = 0;
                    callingLog = null;
                    while (!reader.EndOfStream)
                    {
                        string readLine = reader.ReadLine();
                        if (line++ > 1)
                        {
                            try
                            {
                                //readLine = readLine.Replace("'", "");
                                string[] contents = readLine.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                                //if (contents[4].Trim().ToLower() == "voice")
                                {
                                    DataRow drow = callingLog.NewRow();
                                    drow[cFromNo] = "";//contents[0].Trim();
                                    drow[cFromNet] = "dtac";
                                    string callTo = "0" + contents[1].Trim().Substring(2) ;
                                    drow[cToNo] = callTo;
                                    drow[cToNet] = PrRange.GetProviderFromNumber(callTo);
                                    DateTime onDate = DateTime.ParseExact(contents[0].Trim(), "dd/MM/yyyy HH:mm:ss", null);
                                    drow[cDate] = onDate;
                                    drow[cTime] = onDate.Hour + "." + onDate.Minute;
                                    drow[cHour] = onDate.Hour;
                                    DateTime min = DateTime.ParseExact(contents[4].Trim(), "mm:ss", null);
                                    drow[cMin] = min.Hour * 60 + min.Minute;
                                    callingLog.Rows.Add(drow);

                                    if (!SpecificDateTime.Keys.Contains(onDate.ToString("yyyyMM")))
                                    {
                                        SpecificDateTime.Add(onDate.ToString("yyyyMM"), onDate);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }

                    if (callingLog.Rows.Count > 0)
                    {
                        Response.Redirect("PromoAnalysis.aspx", false);
                    }
                    else
                    {
                        lblError.Text = "Error: Please upload file";
                    }
                }
                else
                {
                    lblError.Text = "Error: Please upload Text file";
                }
            }
            else
            {
                lblError.Text = "Error: Please upload file";
            }
        }
        catch
        {
            lblError.Text = "Error: Please upload well-formed file that you get from provider";
        }
    }

    private void ReadAisFile()
    {
        try
        {

            if (fUpload.PostedFile.ContentLength > 0)
            {
                if (Path.GetExtension(fUpload.FileName).ToLower() == ".txt")
                {
                    StreamReader reader = new StreamReader(fUpload.PostedFile.InputStream);
                    int line = 0;
                    callingLog = null;
                    while (!reader.EndOfStream)
                    {
                        string readLine = reader.ReadLine();
                        if (line++ > 1)
                        {
                            try
                            {
                                //readLine = readLine.Replace("'", "");
                                string[] contents = readLine.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                                //if (contents[4].Trim().ToLower() == "voice")
                                {
                                    DataRow drow = callingLog.NewRow();
                                    drow[cFromNo] = "";//contents[0].Trim();
                                    drow[cFromNet] = "dtac";
                                    string callTo = contents[2].Trim();
                                    drow[cToNo] = callTo;
                                    drow[cToNet] = contents[3].Trim().Replace("DTC","dtac").Replace("TRU", "tmove").Replace("HOM", "home").ToLower(); //PrRange.GetProviderFromNumber(callTo);
                                    DateTime onDate = DateTime.ParseExact(contents[0].Trim() + " " + contents[1].Trim(), "MM/dd/yyyy HH:mm:ss", null);
                                    drow[cDate] = onDate;
                                    drow[cTime] = onDate.Hour + "." + onDate.Minute;
                                    drow[cHour] = onDate.Hour;
                                    DateTime min = DateTime.ParseExact(contents[4].Trim() + ":00", "m:ss", null);
                                    drow[cMin] = min.Hour * 60 + min.Minute;
                                    callingLog.Rows.Add(drow);

                                    if (!SpecificDateTime.Keys.Contains(onDate.ToString("yyyyMM")))
                                    {
                                        SpecificDateTime.Add(onDate.ToString("yyyyMM"), onDate);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }

                    if (callingLog.Rows.Count > 0)
                    {
                        Response.Redirect("PromoAnalysis.aspx", false);
                    }
                    else
                    {
                        lblError.Text = "Error: Please upload file";
                    }
                }
                else
                {
                    lblError.Text = "Error: Please upload Text file";
                }
            }
            else
            {
                lblError.Text = "Error: Please upload file";
            }
        }
        catch
        {
            lblError.Text = "Error: Please upload well-formed file that you get from provider";
        }
    }
}